<?php

namespace app\utils;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class jwt
{
    private $key;

    public function __construct($role)
    {
        $this->key = $role == 'admin' ? env('DEFAULT.ADMIN') : env('DEFAULT.STUDENT');
    }

    public function signToken($user_id){
        $token = array(
            "iss" => $this->key,
            "aud" => '',
            "iat" => time(),
            "nbf" => time(),
            "exp" => time() + 86400,
            "data" => [
                'user_id' => $user_id,
            ]
        );
        $jwt = \Firebase\JWT\JWT::encode($token, $this->key, "HS256");
        return $jwt;
    }

    public function checkoutToken($token){
        $res['status'] = false;
        try {
            \Firebase\JWT\JWT::$leeway = 60;
            $decoded = \Firebase\JWT\JWT::decode($token, new Key($this->key, 'HS256'));
            $arr = (array)$decoded;
            $res['status'] = 200;
            $res['data'] = (array)$arr['data'];
            return $res;

        } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            throw new SignatureInvalidException('签名不正确');
        } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            throw new BeforeValidException('签名在某个时间点之后才能用');
        } catch (\Firebase\JWT\ExpiredException $e) { // token过期
            throw new ExpiredException('token过期');
        } catch (Exception $e) { //其他错误
            throw new \Exception($e->getMessage());
        }
    }
}